//
//  IOTMapVC.m
//  QoilPublic
//
//  Created by SunChao on 2018/4/12.
//  Copyright © 2018年 孙超. All rights reserved.
//

#import "IOTMapVC.h"

#import "Map.h"
#import "DDPointAnnotation.h"
#import "EquipmentCell.h"
#import "CoordinatesModel.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
@interface IOTMapVC ()<UITableViewDataSource,UITableViewDelegate,AMapSearchDelegate>
{
    UIButton *phonebutton;//联系司机
    
    UIControl * _maskView;
    
    UITableView *_tableView;
    NSString *_deviceID;
    AMapSearchAPI *_search;
}
@property (nonatomic, strong) Map *map;
@property (nonatomic,strong) NSMutableArray *locationArray;
@property (nonatomic,strong) NSMutableArray *dataSource;
@end

@implementation IOTMapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(CallOutViewNotification:) name:@"CallOutViewNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AnnotationViewSelNoti:) name:@"AnnotationViewSelNoti" object:nil];
    [self.view addSubview:self.map];
    [self requestALLDeviceData];

}
- (void)AnnotationViewSelNoti:(NSNotification *)noti{
    
    NSString *deviceNum = noti.object;
    [self reuquestSignleDeviceDataWithDeviceID:deviceNum];
}
- (void)CallOutViewNotification:(NSNotification *)noti{
    NSLog(@"noti:%@",noti);
    NSString *deviceNum = noti.object;
    [self reuquestSignleDeviceDataWithDeviceID:deviceNum];
//    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
//
//        _maskView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
//        _maskView.hidden = NO;
//    } completion:^(BOOL finished) {
//
//    }];
    [_tableView reloadData];
}


- (void)createTableView{
    
  
//    _maskView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
//    _maskView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.00];
//    [self.view addSubview:_maskView];
    
//    [_maskView addTarget:self action:@selector(MaskAction) forControlEvents:UIControlEventTouchUpInside];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    _tableView.frame = CGRectMake(10, kScreenHeight - 190-64, kScreenWidth-20, 180);
    
    [_tableView registerNib:[UINib nibWithNibName:@"EquipmentCell" bundle:nil] forCellReuseIdentifier:@"EquipmentCell"];
}
//- (void)MaskAction{
//    
//    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
//
//        _maskView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);
//        _maskView.hidden = YES;
//    } completion:^(BOOL finished) {
//
//    }];
//}
#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    EquipmentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EquipmentCell"];
    [cell setCellWithData:[self.dataSource objectAtIndex:0]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 180;
    
}

- (void)reuquestSignleDeviceDataWithDeviceID:(NSString *)deviceID{
    
    NSString *url = [QParamService urlWithIOTAction:@"map/deviceDetails"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setObject:[QParamService getToken] forKey:@"token"];
    [param setObject:deviceID forKey:@"id"];
    
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if (error) {
            
            NSLog(@"error:%@",basModel.errMsg);
            return ;
        }
        
        if([basModel.result isEqualToString:@"success"]){
            
            NSLog(@"dic:%@",basModel.items);
            NSDictionary *dic = basModel.items;
            CoordinatesModel *model = [CoordinatesModel objectFromDict:dic];
            
            [self addressResolutionWithLat:[model.lat floatValue] lng:[model.lng floatValue]];
            [self.dataSource removeAllObjects];
            [self.dataSource addObject:model];
            [_tableView reloadData];
        }
    }];
    
}

/* 逆地理编码回调. */

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response

{
    
    
    
    if (response.regeocode !=nil )
        
    {
        
        NSLog(@"反向地理编码回调1:%@",response.regeocode.addressComponent.neighborhood);
        
        NSLog(@"反向地理编码回调2:%@",response.regeocode.addressComponent.adcode);
        
        NSLog(@"反向地理编码回调3:%@",response.regeocode.addressComponent.township);
        
        NSLog(@"反向地理编码回调4:%@",response.regeocode.addressComponent.towncode);
        
        NSLog(@"反向地理编码回调5:%@",response.regeocode.addressComponent.district);
        
        NSLog(@"反向地理编码回调6:%@",response.regeocode.formattedAddress);
        for (CoordinatesModel *model in self.dataSource) {
            
            model.formattedAddress = response.regeocode.formattedAddress;
        }
        [_tableView reloadData];
//        NSArray * addressArr = response.regeocode.pois;
        
//        if (addressArr && addressArr.count >0) {
//
//            AMapPOI *poiTemp = addressArr[0];
//
//            NSLog(@"反向地理编码回调:%@",poiTemp.name);
//
//
//
//        }
        
    }

}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}

- (void)addressResolutionWithLat:(CGFloat)lat lng:(CGFloat)lng{
    
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    regeo.location                    = [AMapGeoPoint locationWithLatitude:lat longitude:lng];
    regeo.requireExtension            = YES;
    [_search AMapReGoecodeSearch:regeo];
}
- (void)requestALLDeviceData{


    NSString *url = [QParamService urlWithIOTAction:@"map/deviceList"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setObject:[QParamService getToken] forKey:@"token"];
    [param setObject:@"0" forKey:@"pageNum"];
    [param setObject:@"0" forKey:@"pageSize"];
    [param setObject:@"-1" forKey:@"workStatus"];
    
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {

        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if (error) {

            NSLog(@"error:%@",basModel.errMsg);
            return ;
        }

        if([basModel.result isEqualToString:@"success"]){

            NSLog(@"dic:%@",basModel.items);
            NSArray *array = [NSArray new];
            array = basModel.items;
            for (int i =0; i <array.count; ++i)
            {
                NSDictionary *dic =[array objectAtIndex:i];
                
                float lat = [[dic objectForKey:@"lat"]floatValue];
                float lng = [[dic objectForKey:@"lng"]floatValue];
                NSString *deviceName = [dic objectForKey:@"deviceName"];
                NSString *deviceId = [dic objectForKey:@"id"];
                NSString *workStatus = [dic objectForKey:@"workStatus"];
                
                if (i == 0) {
                    _deviceID = [dic objectForKey:@"id"];
                    [self reuquestSignleDeviceDataWithDeviceID:_deviceID];
                }
                //地图上添加大头针
                DDPointAnnotation *start = [[DDPointAnnotation alloc] init];
                start.title = deviceName;
                start.number = deviceId;
                if ([workStatus isEqualToString:@"1"]) {
                     start.image = [UIImage imageNamed:@"挖掘机"];
                }else{
                     start.image = [UIImage imageNamed:@"挖掘机灰"];
                }
                start.coordinate = CLLocationCoordinate2DMake(lat, lng);
                [self.locationArray addObject:start];
                [self.map.mapView addAnnotation:start];
            
            }
            //设置地图范围
            [self.map.mapView showAnnotations:self.locationArray animated:NO];
             [self createTableView];
        }
    }];

}

- (Map *)map {
    if (!_map) {
        _map = [[Map alloc] initWithFrame:self.view.bounds];
    }
    return _map;
}

ARRAY_INIT(locationArray);
ARRAY_INIT(dataSource);
@end
